package com.nexgo.payment.action.signature;

import android.content.Context;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;

import com.nexgo.payment.R;
import com.nexgo.payment.action.Action;
import com.nexgo.payment.action.ActionResult;
import com.nexgo.payment.action.ActionStep;
import com.nexgo.payment.action.OnActionListener;
import com.nexgo.payment.databases.Repository;
import com.nexgo.payment.entity.SignatureInfo;
import com.nexgo.payment.fragment.SignatureDialogFragment;
import com.nexgo.payment.ui.BaseFragment;
import com.nexgo.payment.util.StringUtils;
import com.nexgo.payment.util.ToastUtils;
import com.nexgo.payment.util.UIUtils;
import com.nexgo.payment.widget.TitleBuilder;
import com.nexgo.payment.widget.signature.view.SignaturePad;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import java8.util.Optional;

/**
 * 电子签名界面
 *
 * @author 谭忠扬-YuriTam
 * @time 2017年08月14日
 */
public class SignatureFragment extends BaseFragment implements Action<ActionStep>, SignatureContract.View, SignaturePad.OnSignedListener, BaseFragment.DownTimerListener {
    private static final String SIGN_CODE = "sign_code";
    private final Logger log;

    @BindView(R.id.signature_pad)
    SignaturePad signaturePad;
    @BindView(R.id.title_tv_right)
    TextView tvTitleRight;
    @BindView(R.id.tv_desc)
    TextView tvDesc;
    @BindView(R.id.btn_confirm)
    Button btnConfirm;
    @BindView(R.id.btn_clear)
    Button btnClear;

    private OnActionListener mListener;
    private SignatureContract.Presenter mPresenter;
    private String mSignCode;
    private Unbinder unbinder;

    public SignatureFragment() {
        log = LoggerFactory.getLogger(getClass().getSimpleName());
    }

    public static SignatureFragment newInstance(String signature) {
        SignatureFragment fragment = new SignatureFragment();
        Bundle args = new Bundle();
        args.putString(SIGN_CODE, signature);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mSignCode = getArguments().getString(SIGN_CODE, StringUtils.leftPad("", 8, '0'));
        }
        new SignaturePresenter(this, Repository.getInstance(), null);
    }

    @Override
    protected View initView(LayoutInflater inflater, ViewGroup container) {
        View view = inflater.inflate(R.layout.fragment_signature, container, false);
        unbinder = ButterKnife.bind(this, view);

        initTitle(view);

        return view;
    }

    //初始化标题栏
    public void initTitle(View view) {
        new TitleBuilder(view)
                .setExternalTitleBgRes(R.drawable.bg_blue_icon)
                .setLeftImage(R.drawable.arrow_icon)
                .setTitleText(getString(R.string.signature_title))
                .build();
    }

    @Override
    protected void initEvent() {
        btnConfirm.setEnabled(false);
        btnClear.setEnabled(false);
    }

    @Override
    protected void initData() {
        signaturePad.setBlock(mSignCode);
        signaturePad.setOnSignedListener(this);
        //启动计时器
        int timeOut = mPresenter.getSignatureTimeout();
        setDownTimer(timeOut < 10 ? 60 : timeOut, this);
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        if (context instanceof OnActionListener) {
            mListener = (OnActionListener) context;
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        mPresenter.start();
    }

    @OnClick({R.id.title_tv_left, R.id.btn_cancel, R.id.btn_clear, R.id.btn_confirm})
    public void onClicked(View view) {
        if (UIUtils.isDoubleClick()) {
            return;
        }
        switch (view.getId()) {
            //取消
            case R.id.title_tv_left:
            case R.id.btn_cancel:
                if (mListener != null) {
                    mListener.setActionResult(new ActionResult(SignatureFragment.this, ActionResult.ERR_CANCEL, null));
                }
                break;
            //重签
            case R.id.btn_clear:
                mPresenter.clearSignature();
                break;
            //确认签名
            case R.id.btn_confirm:
                mPresenter.customerConfirmSignature(signaturePad.getSignatureBitmap());
                break;
            default:
                break;
        }
    }

    @Override
    public void onStartSigning() {

    }

    @Override
    public void onSigned() {
        btnConfirm.setEnabled(true);
        btnClear.setEnabled(true);
    }

    @Override
    public void onClear() {
        btnConfirm.setEnabled(false);
        btnClear.setEnabled(false);
    }

    @Override
    public void onStop() {
        super.onStop();
    }

    @Override
    public ActionStep getActionStep() {
        return ActionStep.ELECTRONIC_SIGNATURE;
    }

    @Override
    public void setPresenter(SignatureContract.Presenter presenter) {
        mPresenter = presenter;
    }

    @Override
    public void showMaxSignatureTimes() {
        ToastUtils.showToast(getString(R.string.beyond_re_sign_times));
        if (mListener != null) {
            mListener.setActionResult(new ActionResult(SignatureFragment.this, ActionResult.ERR_FAIL, null));
        }
    }

    @Override
    public void clearSignature(int tryTimes) {
        tvDesc.setText(getString(R.string.pls_sign_above_block) + "（" + tryTimes + "）");
        signaturePad.clear();
        btnConfirm.setEnabled(false);
        btnClear.setEnabled(false);
        restartDownTimer();
    }

    @Override
    public void showSignatureConfirm(Bitmap bitmap) {
        SignatureDialogFragment dialogFragment = new SignatureDialogFragment();
        dialogFragment.setDialogType(SignatureDialogFragment.DIALOG_TYPE_WARNING);
        dialogFragment.setTitleText(getString(R.string.pls_confirm_signature));
        dialogFragment.setBitmap(bitmap);
        dialogFragment.setPositionText(getString(R.string.confirm));
        dialogFragment.setNegativeText(getString(R.string.cancel));
        dialogFragment.setDialogListener(new SignatureDialogFragment.OnDialogListener() {

            @Override
            public void onCancel() {
                mPresenter.operatorConfirmSignature(false);
            }

            @Override
            public void onConfirm() {
                mPresenter.operatorConfirmSignature(true);
            }
        });
        dialogFragment.show(getActivity().getSupportFragmentManager(), null);
    }

    @Override
    public void showSignatureFinish(SignatureInfo info) {
        cancelDownTimer();
        //返回签名数据
        if (mListener != null) {
            mListener.setActionResult(new ActionResult(SignatureFragment.this, ActionResult.SUCC, info));
        }
    }

    @Override
    public void showSignatureErr() {
        ToastUtils.showToast(R.string.signature_init_err);
        if (mListener != null) {
            mListener.setActionResult(new ActionResult(SignatureFragment.this, ActionResult.ERR_FAIL, null));
        }
    }

    @Override
    public void showSignatureTooComplicated() {
        mPresenter.signatureTooComplicate();
    }

    @Override
    public void showSignatureFail() {
        if (mListener != null) {
            mListener.setActionResult(new ActionResult(SignatureFragment.this, ActionResult.ERR_FAIL, null));
        }
    }

    @Override
    public void showToast(String message) {
        Optional.ofNullable(message)
                .filter(s -> !TextUtils.isEmpty(s))
                .ifPresent(s -> ToastUtils.showToast(s));
    }

    @Override
    public boolean isActive() {
        return isAdded();
    }

    @Override
    public void onTick(long secondsUntilFinished) {
        if (!isActive()) {
            return;
        }
        tvTitleRight.setVisibility(View.VISIBLE);
        tvTitleRight.setText(String.valueOf(secondsUntilFinished));
    }

    @Override
    public void onFinish() {
        ToastUtils.showToast(R.string.signature_time_out);
        if (isActive()) {
            tvTitleRight.setText("0");
        }
        if (mListener != null) {
            mListener.setActionResult(new ActionResult(SignatureFragment.this, ActionResult.ERR_TIMEOUT, null));
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        //取消计时器
        cancelDownTimer();
        unbinder.unbind();
    }
}
